﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DIProject.ReceptionGoods
{
    public partial class NewAssGoodsInputLines : Form
    {
        private Int32 _docId;
        WaybillsImportList _par;
        public NewAssGoodsInputLines(Int32 docId, WaybillsImportList par)
        {
            _docId = docId;
            _par = par;
            InitializeComponent();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            tabContainer.SelectedIndex = 1;
        }

        private void btnPrevision_Click(object sender, EventArgs e)
        {
            tabContainer.SelectedIndex = 0;
        }

        private void btnNext1_Click(object sender, EventArgs e)
        {
            tabContainer.SelectedIndex = 2;
        }

        private void btnPrevision1_Click(object sender, EventArgs e)
        {
            tabContainer.SelectedIndex = 1;
        }
        /// <summary>
        /// Сохранение товара
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            AddAll();
        }

        private void tabContainer_SelectedIndexChanged(object sender, EventArgs e)
        {
            Int32 tmp = tabContainer.SelectedIndex;
            switch (tmp)
            {
                case 0:
                    this.AcceptButton = btnNext;
                    break;
                case 1:
                    this.AcceptButton = btnNext1;
                    break;
                case 2:
                    this.AcceptButton = btnSave;
                    break;
                default:
                    return;
            }
        }

        private void txbName_Validating(object sender, CancelEventArgs e)
        {
            e.Cancel = NameValidate();
        }
        private void InitComboBoxes()
        {
            if (cbCatalog.DataSource == null)
                cbCatalog.DataSource = Data.Catalog.Data;
            if (cbMedForm.DataSource == null)
                cbMedForm.DataSource = Data.MedForm.Data;
            if (cbAssesGroup.DataSource == null)
                cbAssesGroup.DataSource = Data.AssortmentGroup.Data;
            if (cbManufacturer.DataSource == null)
                cbManufacturer.DataSource = new Data.Test2().Data;
            if (cbCountry.DataSource == null)
                cbCountry.DataSource = Data.Country.Data;
            if (cbCertificateOrg.DataSource == null)
                cbCertificateOrg.DataSource = new Data.CertificatedOrg().Data;
        }

        private void NewAssGoodsInputLines_Load(object sender, EventArgs e)
        {
            InitComboBoxes();
            /*cbCatalog.SelectedValue = 1;
           // cbCatalog.SelectedValue = Util.Karantin.KarantinGroupId;
            cbMedForm.SelectedValue = 1;
            cbCountry.SelectedValue = 1;
            cbManufacturer.SelectedValue = 1;
            cbAssesGroup.SelectedValue = 1;
            cbCertificateOrg.SelectedValue = 1;*/
            SetComboBoxes();
        }

        private void tabAssortment_Validated(object sender, EventArgs e)
        {
            
        }

        private void tabAssortment_Validating(object sender, CancelEventArgs e)
        {
            e.Cancel = NameValidate();
        }
        bool flagName = false;
        private bool NameValidate()
        {
            if (flagName)
            {
                flagName = false;
                return false;
            }
            if (string.IsNullOrEmpty(txbName.Text))
            {
                MessageBox.Show("Неоходимо ввести наименование товара", "Введите наименование", MessageBoxButtons.OK, MessageBoxIcon.Error);
                tabContainer.SelectedIndex = 0;
                txbName.Focus();                
                return true;
            }
            return false;
        }
        #region Методы для всиавки данных
        private Int32 AddAssortment()
        {
            try
            {
                DataSets.DictionaryTableAdapters.QueriesTableAdapter query = new DIProject.DataSets.DictionaryTableAdapters.QueriesTableAdapter();
                object obj = query.AssortmentQuery(this.txbName.Text, (Int32)this.cbMedForm.SelectedValue);
                if ((!Convert.IsDBNull(obj) && obj != null))
                {
                    return (Int32)obj;
                }
                DataSets.DictionaryTableAdapters.AssortmentTableAdapter adapter = new DIProject.DataSets.DictionaryTableAdapters.AssortmentTableAdapter();
                DataSets.Dictionary.AssortmentDataTable insRow = new DIProject.DataSets.Dictionary.AssortmentDataTable();
                DataSets.Dictionary.AssortmentRow ar = insRow.NewAssortmentRow();
                ar.Name = this.txbName.Text;
                ar.CatalogId = (Int32)this.cbCatalog.SelectedValue;
                ar.MedFormId = (Int32)this.cbMedForm.SelectedValue;
                ar.AssesmentGroupId = (Int32)this.cbAssesGroup.SelectedValue;
                ar.ABList = this.txbListAB.Text;
               /// ar.NotPatentedRus = this.txbNonPatentRus.Text;
              //  ar.NotPatentedLat = this.txbNonPatentLat.Text;
                ar.GNVLS = this.cbxGNVLS.Checked;
                ar.Mandatory = this.cbxMandatory.Checked;
              //  if (this.numericBeforeOverdue.Value > 0)
               //     ar.BeforeOverdue = Convert.ToByte(this.numericBeforeOverdue.Value);
                ar.NoRecipe = this.cbxNoRecipe.Checked;
                ar.Note = this.txbNote.Text;
                ar.MW = FirstForm.Login;
                ar.MD = DateTime.Now;
                ar.ToDelete = false;
                insRow.Rows.Add(ar);
                adapter.Update(insRow);
                DataSets.UtilTableAdapters.UtilQueries aa = new DIProject.DataSets.UtilTableAdapters.UtilQueries();
                
                Int32 res = aa.GetLastAssortmentId().Value;
                return res;
            }
            catch (Exception e)
            {
                throw new Util.DIException("Невозможно добавить новый ассортимент", e);
            }
        }
        private DataSets.Dictionary.GoodsRow CurrentRow;
        private Int32 AddGood(Int32 assId)
        {
            try
            {
                DataSets.DictionaryTableAdapters.QueriesTableAdapter query = new DIProject.DataSets.DictionaryTableAdapters.QueriesTableAdapter();
                Int32 rPack = Int32.MinValue;
                if(!string.IsNullOrEmpty(txbRetailPack.Text))
                {
                    rPack = Convert.ToInt32(txbRetailPack.Text);
                }
                object obj = query.GoodsQuery(assId, (Int32)cbManufacturer.SelectedValue, (Int32)cbCountry.SelectedValue, rPack);
                if ((!Convert.IsDBNull(obj) && obj != null))
                {
                    return (Int32)obj;
                }
                DataSets.DictionaryTableAdapters.GoodsTableAdapter adapter = new DIProject.DataSets.DictionaryTableAdapters.GoodsTableAdapter();
                DataSets.Dictionary.GoodsDataTable tab = new DIProject.DataSets.Dictionary.GoodsDataTable();
                this.CurrentRow = tab.NewGoodsRow();
                this.CurrentRow.AssortmentId = assId;
                this.CurrentRow.ManufacturerId = (Int32)cbManufacturer.SelectedValue;
                this.CurrentRow.CountryId = (Int32)cbCountry.SelectedValue;
                this.CurrentRow.AllowUnPack = cbxAllowUnPack.Checked;
                if(!string.IsNullOrEmpty(txbRetailPack.Text))
                    this.CurrentRow.RetailPack = Convert.ToInt32(txbRetailPack.Text);
                if(!string.IsNullOrEmpty(txbWholesalePack.Text))
                    this.CurrentRow.WholesalePack = Convert.ToInt32(txbWholesalePack.Text);
                if(!string.IsNullOrEmpty(txbManufactureBarCode.Text))
                    this.CurrentRow.ManufactureBarCode = txbManufactureBarCode.Text;
                if (!string.IsNullOrEmpty(this.txbFixedPrice.Text))
                    this.CurrentRow.FixedPrice = Convert.ToDecimal(this.txbFixedPrice.Text);
                if (!string.IsNullOrEmpty(this.txbNote.Text))
                    this.CurrentRow.Note = this.txbNote.Text;
                this.CurrentRow.MD = DateTime.Now;
                this.CurrentRow.MW = FirstForm.Login;
                CurrentRow.ToDelete = false;
                this.CurrentRow.DefekturaAggregate = cbAgregative.Checked;
                tab.Rows.Add(this.CurrentRow);
                adapter.Update(tab);
                DataSets.UtilTableAdapters.UtilQueries aa = new DIProject.DataSets.UtilTableAdapters.UtilQueries();
                Int32 res = aa.GetLastGoodsId().Value;
                return res;
            }
            catch (Exception e)
            {
                throw new Util.DIException("Невозможно добавить новый товар", e);
            }
        }
        private decimal CalcSummNoNDS
        {
            get
            {
                if (string.IsNullOrEmpty(txbCount.Text))
                    return 0;
                if (string.IsNullOrEmpty(txbNDSTax.Text))
                    return 0;
                if (string.IsNullOrEmpty(txbSupplierPrice.Text))
                    return 0;
                decimal sPrice;
                Int32 count;
                byte nds;
                string str = txbSupplierPrice.Text.Replace(',', '.');
                if (!decimal.TryParse(str, out sPrice))
                    return 0;
                if (!Int32.TryParse(txbCount.Text, out count))
                    return 0;
                if (!byte.TryParse(txbNDSTax.Text, out nds))
                    return 0;
                decimal result = (count * sPrice * 100) / Convert.ToDecimal(100 + nds);
                return result;
            }
        }
        private void AddNewPartiesRow(Int32 goodsId)
        {
            object ReadyBefore = null;
            if (this.dtpReadyBefore.Checked)
                ReadyBefore = this.dtpReadyBefore.Value;
            object MadeDate = null;
            if (this.dtpMadeDate.Checked)
                MadeDate = this.dtpMadeDate.Value;
            object ReestrDate = null;
            if (this.dtpReestrDate.Checked)
                ReestrDate = this.dtpReestrDate.Value;
            object CertificateDate = null;
            if (this.dtpCertificateDate.Checked)
                CertificateDate = this.dtpCertificateDate.Value;
            byte NDSTax = 10;
            if (!string.IsNullOrEmpty(this.txbNDSTax.Text))
                NDSTax = Convert.ToByte(this.txbNDSTax.Text);
            DIProject.Data.Nkld.SupplierInvoiceLinesInsert(_docId, goodsId, null,
                Convert.ToInt32(this.txbCount.Text), Util.Convert.ToInt32(this.txbCount.Text), 1,
                Util.Convert.ToDecimal(this.txbManufacturerPrice.Text), Util.Convert.ToDecimal(this.txbSupplierPrice.Text),
                this.CalcSummNoNDS,// Util.Convert.ToDecimal(txbSummNoNDS.Text),
                Util.Convert.ToDouble(this.txbImportMarkUp.Text), Util.Convert.ToDouble(this.txbSupplierMarkUp.Text),
                this.txbSerija.Text, Util.Convert.ToDateTime(ReadyBefore), Util.Convert.ToDateTime(MadeDate),
                NDSTax, Util.Convert.ToDecimal(this.txbNDSSumm.Text), Util.Convert.ToDecimal(this.txbReestrPrice.Text),
                Util.Convert.ToDateTime(ReestrDate), this.txbGTDNumber.Text, this.txbCertificateNumber.Text,
                Util.Convert.ToDateTime(CertificateDate), (Int32)this.cbCertificateOrg.SelectedValue,
                Util.Convert.ToDouble(this.txbMarkUp.Text), Util.Convert.ToDecimal(this.txbRetailPrice.Text),
                this.txbNote.Text, DateTime.Now, FirstForm.Login);
            _par.lbNaklList_DoubleClick(_par.lbNaklList, EventArgs.Empty);
        }
        private void AddAll()
        {
            Int32 tmp;
            tmp = AddAssortment();
            tmp = AddGood(tmp);
            AddNewPartiesRow(tmp);
            this.Close();
        }
        #endregion

        private void txbCount_Validating(object sender, CancelEventArgs e)
        {
            e.Cancel = !Util.Validator.Int32Validation(txbCount, string.Empty);
        }

        private void txbRetailPrice_Validating(object sender, CancelEventArgs e)
        {
            e.Cancel = !Util.Validator.DecimalValidation(txbRetailPrice, string.Empty);
        }

        private void txbNDSTax_Validating(object sender, CancelEventArgs e)
        {
            e.Cancel = !Util.Validator.Int32Validation(txbNDSTax, string.Empty);
        }

        private void txbWholesalePack_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(txbWholesalePack.Text))
            {
                MessageBox.Show("Введите \"Количество в разделяемой упаковке\"");
                txbWholesalePack.Focus();
                return;
            }
            e.Cancel = !Util.Validator.Int32Validation(txbWholesalePack, string.Empty);
        }

        private void txbRetailPack_Validating(object sender, CancelEventArgs e)
        {
            if (string.IsNullOrEmpty(txbRetailPack.Text))
            {
                MessageBox.Show("Введите \"Количество в разделяемой упаковке\"");
                txbRetailPack.Focus();
                return;
            }
            e.Cancel = !Util.Validator.Int32Validation(txbRetailPack, string.Empty);
        }
        private void SetComboBoxes()
        {
           // InitComboBoxes();
            cbCatalog.SelectedValue = 1;
            // cbCatalog.SelectedValue = Util.Karantin.KarantinGroupId;
            cbMedForm.SelectedValue = 1;
            cbCountry.SelectedValue = 1;
            cbManufacturer.SelectedValue = 1;
            cbAssesGroup.SelectedValue = 1;
            cbCertificateOrg.SelectedValue = 1;
        }
        private void NewAssGoodsInputLines_Shown(object sender, EventArgs e)
        {
            SetComboBoxes();
        }
    }
}